package com.mirzabros.chexmo.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.mirzabros.chexmo.Chexmo_Add_Pin;
import com.mirzabros.chexmo.Chexmo_Chk_Pin;
import com.mirzabros.chexmo.Chexmo_Store_Login;

public class Chexmo_MobileNo_Check_Service extends AsyncTask<String, Void, String> {

	private ProgressDialog progdialod;
	private Activity activity;
	private Context context;
	
	public static Cookie cookie = null;
	
	private boolean exeption = false;
	
	private String userName;
	private String password;
	private String code;
	private String number;
	private String logo;
	
	// connection establish timeout (timeoutConnection)
	private int timeoutConnection = 5000;
	// socket timeout (timeoutSocket) 
	private int timeoutSocket = 45000;

	JSONArray jArray;
	
	static InputStream is = null;
	static JSONObject jobj = null;
	static String json = ""; 
	List<NameValuePair> params;
	HttpParams httpParameters = new BasicHttpParams();

	
	public Chexmo_MobileNo_Check_Service(Activity activity,String user,String password,String code,String number,String logo) {
		super();
		this.activity = activity;
		this.context = this.activity.getApplicationContext();
		this.userName = user;
		this.password = password;
		this.code = code;
		this.number = number;
		this.logo = logo;
		
		Log.d("userName", userName);
		Log.d("password", password);
	}
	
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progdialod = ProgressDialog.show(this.activity, "Check Mobile", "Checking Mobile Number, Please Wait",true,false);
	}
	
	
	@Override
	protected String doInBackground(String... urls) {
		
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		
		try {
			
			HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);			
			HttpClient httpclient = new DefaultHttpClient(httpParameters);
			
			List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("key", code));
            params.add(new BasicNameValuePair("mobile", number));
			
			/*HttpPost httppost = new HttpPost(RegisterUserLink);*/
			HttpPost httppost = new HttpPost(urls[0]);
			JSONObject json = new JSONObject();
			
			json.put("key", code);//Token Code
			json.put("mobile", number);

			JSONArray postjson = new JSONArray();
			postjson.put(json);
			httppost.setHeader("json", json.toString());

			httppost.getParams().setParameter("jsonpost", postjson);
			httppost.setEntity(new UrlEncodedFormEntity(
					params));
			HttpResponse httpResponse = httpclient.execute(httppost);
			
			HttpEntity httpEntity = httpResponse.getEntity();

			is = httpEntity.getContent();
			
			}catch (UnsupportedEncodingException e) {
				exeption = true;
				e.printStackTrace();
			}catch (ClientProtocolException e) {
				exeption = true;
				e.printStackTrace();
			} catch (IOException e) {   
				exeption = true;
				e.printStackTrace();
			} catch (JSONException e) {
				exeption = true;
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try{
				BufferedReader reader=new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
				StringBuilder sb=new StringBuilder();
				
				String line=null;
				
				while((line=reader.readLine())!=null){
					//sb.append(line+"n");
					sb.append(line);
				}
				is.close();
				json=sb.toString();
				
				Log.e("JSON RES:",json);
				
			}catch(Exception e){
				exeption = true;
				Log.e("Buffer Error","Error converting result"+e.toString());
			}
		 return json;
		
	}
	
	@Override
	protected void onPostExecute(String result) {
		
		Log.d("Post Exec", "POST EXEC");
		
		Log.d("Post tt", result);
		progdialod.dismiss();

		
		Log.d("Post Exec Check Mobile", result);
		
		
		
		if(result.trim().equals("fail")){
			Toast toast = Toast.makeText(activity, "Mobile No Not in DB !!", Toast.LENGTH_SHORT);
			toast.show();
			
			
			Intent intent = new Intent(activity,Chexmo_Add_Pin.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			Bundle bundle = new Bundle();
			bundle.putString("user", userName);
			bundle.putString("pass", password);
			bundle.putString("code", code);
			bundle.putString("number", number);
			bundle.putString("logo", logo);
			intent.putExtras(bundle);
			activity.startActivity(intent);
			
		}else{
			if(!exeption){
				
				if(result.length()<9){ 
					Toast toast = Toast.makeText(activity, "Success !!", Toast.LENGTH_SHORT);
					toast.show();

					Intent intent = new Intent(activity,Chexmo_Chk_Pin.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					Bundle bundle = new Bundle();
					bundle.putString("user", userName);
					bundle.putString("pass", password);
					bundle.putString("code", code);
					bundle.putString("number", number);
					bundle.putString("logo", logo);
					intent.putExtras(bundle);
					activity.startActivity(intent);
				}
				
			    else if(!result.substring(0,9).equals("<!DOCTYPE")){
			 		Toast toast = Toast.makeText(activity, "Success !!", Toast.LENGTH_SHORT);
					toast.show();

					Intent intent = new Intent(activity,Chexmo_Chk_Pin.class);
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					Bundle bundle = new Bundle();
					bundle.putString("user", userName);
					bundle.putString("pass", password);
					bundle.putString("code", code);
					bundle.putString("number", number);
					bundle.putString("logo", logo);
					intent.putExtras(bundle);
					activity.startActivity(intent);
				}else{
					Toast toast = Toast.makeText(activity, "Mobile Number Check Exeption !!", Toast.LENGTH_SHORT);
					toast.show();
				}

			}else{
				Toast toast = Toast.makeText(activity, "Mobile Number Check Exeption !!", Toast.LENGTH_SHORT);
				toast.show();
			}
		}

		/*Toast toast = Toast.makeText(activity, "UserName Or Password Incorrect. Login Failed !!", Toast.LENGTH_SHORT);
		toast.show();*/
		
		
	}


}
